#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(QString("%1 %2").arg(m_windowTitle.c_str(), RELEASE_VERSION));
    m_httpRequest.setRawHeader("Connection", "Keep-Alive");
    m_httpRequest.setRawHeader("User-Agent", "1601");
    m_httpRequest.setUrl(QUrl(QString("http://%1:81/stream").arg(ui->ipAddr->text())));
    QIcon icon;
    icon.addFile(":/menu/images/stop.png");
    ui->startAndStop->setIcon(icon);
    ui->startAndStop->setIconSize(QSize(25, 25));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showPixmap(QPixmap pixmap)
{
    QPixmap pps = pixmap.scaled(ui->video->width(), ui->video->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->video->setPixmap(pps);
}

void MainWindow::httpResponse()
{
    // 打印接收内容
    QByteArray buffer = m_httpClient->readAll();
    const QString startKey = "Content-Type: image/jpeg\r\nContent-Length: ";
    const QString endKey = "\r\n--123456789000000000000987654321\r\n";
    const QString splitKey = "\r\n\r\n";
    int startPos = buffer.indexOf(startKey);
    int endPos = buffer.indexOf(endKey);
    if (startPos >= 0 && endPos >= 0) {
        if (startPos < endPos) {
            QByteArray lastFrame = buffer.mid(0, startPos);
            frameBuffer.append(lastFrame);
            // 显示
            this->showPixmap(frameBuffer);
            frameBuffer.clear();
            int splitPos = buffer.indexOf(splitKey, startPos) + splitKey.size();
            QByteArray currentFrame = buffer.mid(splitPos, endPos - splitPos);
            frameBuffer.append(currentFrame);
            // 显示
            this->showPixmap(frameBuffer);
            frameBuffer.clear();
            QByteArray nextFrame = buffer.mid(endPos + endKey.size());
            frameBuffer.append(nextFrame);
        } else {
            QByteArray lastFrame = buffer.mid(0, endPos);
            frameBuffer.append(lastFrame);
            // 显示
            this->showPixmap(frameBuffer);
            frameBuffer.clear();
            int splitPos = buffer.indexOf(splitKey, startPos) + splitKey.size();
            QByteArray nextFrame = buffer.mid(splitPos);
            frameBuffer.append(nextFrame);
        }
        return;
    }
    if (startPos >= 0) {
        QByteArray lastFrame = buffer.mid(0, startPos);
        frameBuffer.append(lastFrame);
        // 显示
        this->showPixmap(frameBuffer);
        frameBuffer.clear();
        int splitPos = buffer.indexOf(splitKey, startPos);
        QByteArray nextFrame = buffer.mid(splitPos + splitKey.size());
        frameBuffer.append(nextFrame);
        return;
    }
    if (endPos >= 0) {
        QByteArray lastFrame = buffer.mid(0, endPos);
        frameBuffer.append(lastFrame);
        // 显示
        this->showPixmap(frameBuffer);
        frameBuffer.clear();
        QByteArray nextFrame = buffer.mid(endPos + endKey.size());
        frameBuffer.append(nextFrame);
        return;
    }
    frameBuffer.append(buffer);
}

void MainWindow::showPixmap(QByteArray buffer)
{
    QPixmap pixmap;
    bool loadStatus = pixmap.loadFromData(buffer);
    if (!loadStatus) {
        qDebug() << "Video load failed";
        frameBuffer.clear();
        return;
    }
    this->showPixmap(pixmap);
}


void MainWindow::on_saveImage_clicked()
{
}


void MainWindow::on_pixelSelect_currentIndexChanged(int index)
{
    QString httpUrl = QString("http://%1/control?var=framesize&val=%2").arg(ui->ipAddr->text()).arg(index);
    m_contrlRequest.setRawHeader("Connection", "Keep-Alive");
    m_contrlRequest.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
    m_contrlRequest.setUrl(QUrl(httpUrl));
    qDebug() << httpUrl;
    if (m_contrlClient != nullptr) {
        m_contrlClient->abort();
    }
    m_contrlClient = m_contrlManager.get(m_contrlRequest);
    connect(m_contrlClient, &QNetworkReply::readyRead, this, [&]{
        qDebug() << "修改成功";
        qDebug() << m_contrlClient->readAll();
    });
    connect(m_contrlClient, &QNetworkReply::finished, this, [&]{
        m_contrlClient->deleteLater();
        m_contrlClient = nullptr;
    });
}


void MainWindow::on_startAndStop_clicked()
{
    if (m_startAndStopFlag) {
        qDebug() << "stop";
        m_startAndStopFlag = false;
        QIcon icon;
        icon.addFile(":/menu/images/stop.png");
        ui->startAndStop->setIcon(icon);
        ui->startAndStop->setIconSize(QSize(25, 25));
        m_httpClient->abort();
        frameBuffer.clear();
    } else {
        qDebug() << "start";
        m_startAndStopFlag = true;
        QIcon icon;
        icon.addFile(":/menu/images/start.png");
        ui->startAndStop->setIcon(icon);
        ui->startAndStop->setIconSize(QSize(25, 25));
        if (m_httpClient != nullptr) {
            m_httpClient->abort();
            frameBuffer.clear();
        }
        m_httpClient = m_httpManager.get(m_httpRequest);
        connect(m_httpClient, &QNetworkReply::readyRead, this, &MainWindow::httpResponse);
        connect(m_httpClient, &QNetworkReply::finished, this, [&]{
            m_httpClient->deleteLater();
            m_httpClient = nullptr;
        });
    }
}
